<?php

namespace app\api\model;

use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\model\relation\HasOne;

class GoodsCart extends BaseModel
{
    protected $table = 'fa_store_cart';
    protected $type = [
        'specifications' => 'array',
        'checked' => 'boolean'
    ];
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取用户所有的购物车列表
     * @param $userid
     * @return bool|\PDOStatement|string|Collection
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getCartList($userid)
    {
        return self::where('user_id', $userid)
            ->where('type',1)
            ->with(['merchant' => function ($query) {
            $query->field('id,trade_name');
        }])->select();
    }

    /**
     * 装饰商家名
     * @param $list
     * @return void
     */
    public static function decorationMerchant(&$list)
    {
        foreach ($list as &$v) {
            $v['merchant'] = $v['merchant']['trade_name'];
            unset($v);
        }
        unset($list);
    }

    public static function getCartById($id, $userid)
    {
        return self::where('id', $id)->where('user_id', $userid)->find();
    }

    public static function getCartByIds($userid, $cartIds)
    {
        return self::where('user_id', $userid)->whereIn('id', $cartIds)->select();
    }

    /**
     * 关联商家
     * @return HasOne
     */
    public function merchant(): HasOne
    {
        return $this->hasOne(JoinMerchant::class, 'id', 'merchant_id');
    }

    /**
     * 关联货品
     * @return HasOne
     */
    public function product(): HasOne
    {
        return $this->hasOne(GoodsProduct::class, 'id', 'product_id');
    }
}